package com.kfm.mvn.servlet;

import com.kfm.mvn.model.User;
import com.kfm.mvn.service.UserService;
import com.kfm.mvn.util.Constant;
import com.wf.captcha.utils.CaptchaUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String captcha = req.getParameter("captcha");

        final String CONTEXT_PATH = req.getContextPath();

        // 验证码校验
        if (!CaptchaUtil.ver(captcha, req)){
            // 清除验证码
            CaptchaUtil.clear(req);
            // 重定向
            resp.sendRedirect(CONTEXT_PATH + "/");
            return;
        }
        // 清除验证码
        CaptchaUtil.clear(req);

        // 登录业务
        User user = userService.login(username, password);

        if (user == null){
            // 用户名或密码不正确
            resp.sendRedirect(CONTEXT_PATH + "/");
            return;
        }

        // 登录成功
        req.getSession().setAttribute(Constant.LOGIN_USER, user);
        resp.sendRedirect(CONTEXT_PATH + "/welcome");
    }
}
